package com.my.dao.impl;

import java.math.BigInteger;
import java.util.List;

import com.my.bean.User;
import com.my.dao.IBaseDAO;
import com.my.dao.UserDAO;

public class UserDAOImpl implements UserDAO {
	private IBaseDAO<User> basedao;

	public void setBasedao(IBaseDAO<User> basedao) {
		this.basedao = basedao;
	}

	@Override
	public boolean addUser(User user) throws Exception {
		if (this.checkUser(user)) {
			return basedao.add(user);
		}
		return false;
	}

	@Override
	public boolean editUser(User user) throws Exception {
		if (this.checkUser(user)) {
			return basedao.edit(user);
		}
		return false;
	}

	@Override
	public User getUserById(Class<User> c, Integer id) throws Exception {
		return basedao.getById(c, id);
	}

	@Override
	public boolean removeUser(Integer id) throws Exception {
		User user = basedao.getById(User.class, id);
		if (user != null) {
			basedao.remove(user);
		}
		return false;
	}

	@Override
	public BigInteger getTotalUserRecords() throws Exception {
		String sql = "select count(user_id) from info_user";
		return basedao.getTotalRecords(sql);
	}

	@Override
	public List<User> getAllUserByPage(int pageindex, int pagesize)
			throws Exception {
		String hql = "from User";
		return basedao.getAllEntityByPage(hql, pageindex, pagesize);
	}

	@Override
	public BigInteger searchTotalUserRecords(User user) throws Exception {
		String sql = "select count(user_id) from info_user where user_name like ? and province like ? and city like ?";
		String item1 = user.getName() + "%";
		String item2 = user.getProvince() + "%";
		String item3 = user.getCity() + "%";
		return basedao.getTotalRecords(sql, item1, item2, item3);
	}

	@Override
	public List<User> searchUserByPage(int pageindex, int pagesize, User user)
			throws Exception {
		String hql = "from User as u where u.name like ? and u.province like ? and city like ?";
		String item1 = user.getName() + "%";
		String item2 = user.getProvince() + "%";
		String item3 = user.getCity() + "%";
		return basedao.getAllEntityByPage(hql, pageindex, pagesize, item1,
				item2, item3);
	}

	boolean checkUser(User user) {
		if (user == null) {
			return false;
		} else {
			return true;
		}
	}

}
